﻿//DOM樹加載完成
$(function () {

    window.isFirstLoad = true;//是否是首次加載數據
    window.sortField = null;
    window.isDesc = null;
    window.$tbody = $("#tbody");
    window.imgSrc1 = "../../images/plus.gif"; //收缩
    window.imgSrc2 = "../../images/subtract.gif";//展开

    $.templates({
        listTemplate: $('#listTemplate').text(),
        selectFirstDeep: $('#selectFirstDeep').text()
    }); //加载jsrender模板

    $("[name='aSort']").click(sort); //点击排序

    display(); //展开数据
    ChangeDropDown(); //dropdown添加处理
    GetFirstDeep();
    expandAll($('#expendchk'));
});
//展开列表
function display() {
    $(document).on('click', '#tbody tr td img[clickopen="1"]', function () { //为小图片绑定点击事件
        var $img = $(this);
        var $tr = $(this).parents('tr');
        var id = parseInt($tr.attr('id'));
        var clicked = $tr.attr('clicked');
        var src = $img.attr('src');

        if (clicked === "false") { //最开始是收缩状态
            $tr.attr('clicked', "true");
            if (src === window.imgSrc1) {
                $img.attr('src', window.imgSrc2);
            }
            $('#tbody tr[pid=' + id + ']').show();//展开的时候只要展开下一层就好了
        } else {
            try {
                if (src === window.imgSrc2) {
                    $img.attr('src', window.imgSrc1);
                }
                $tr.attr('clicked', "false");
                close(id);
            } catch (e) {
                $img.attr('src', window.imgSrc2);
                $tr.attr('clicked', "true");
            }
        }
    });
}
//关闭列表
function close(id) {
    var children = $('#tbody tr[pid=' + id + ']');
    if (children != undefined) {
        var $tr;
        for (var i = 0; i < children.length; i++) {
            $tr = $(children).eq(i);
            var id1 = parseInt($tr.attr('id'));
            var $img = $tr.find('img');
            if ($img != undefined) {
                var src = $img.attr('src');
                if (src === window.imgSrc2) {
                    $img.attr('src', window.imgSrc1);
                }
                $tr.attr('clicked', "false");
            }
            close(id1);
        }
    }
    $(children).hide();
}
//下拉框改变
function ChangeDropDown() {
    $(document).on('click', '#ddlParent.dropdown ul li', function () {
        var button = $(this).parents('#ddlParent.dropdown').find('button');
        if (button != undefined) {
            button.html($(this).html() + ' <span class="caret"></span>');
            button.attr('fid', $(this).attr('fid'));
        }
    });
};
//获取第一级菜单
function GetFirstDeep() {
    var url = 'handler.ashx?Operate=GetFirstDeep';
    $.get(url, { SiteId: SiteId, ChannelId: ChannelId, CMId: CMId }, function (ajaxMsg) {
        if (ajaxMsg.status === 1) {
            if (ajaxMsg.data.length > 0)
                var html = $.render.selectFirstDeep(ajaxMsg.data);
            $(html).insertAfter($('#ddlParent-menu li:eq(0)'));
        } else {
            msgBox.showMsgErr(ajaxMsg.data);
        }
    }).done(function () {
        getFiledList(); //加载数据
    });
}

//獲取排序字段和方法
function getSortInfo() {
    if (sortField == null) {
        var $spanDirection = $("span[class='glyphicon glyphicon-triangle-bottom xuanzhuanss']");
        if ($spanDirection.length == 0) {
            $spanDirection = $("span[class='glyphicon glyphicon-triangle-bottom']");
        }

        if ($spanDirection.length > 0) {
            sortField = $spanDirection.prev().attr("field");
            if ($spanDirection.hasClass("xuanzhuanss")) {
                isDesc = false;
            }
            else {
                isDesc = true;
            }
        }
    }

    if (isDesc == null) {
        isDesc = false;
    }
}

//获取字段列表
//sortField 排序字段
//isDesc 是否是降序
function getFiledList(page) {
    msgBox.showMsgWait(txt_Loading); //显示消息面板

    var isShow = $("#ddlIsShow").val();
    var keyword = $("#txtKeyword").val();

    getSortInfo();

    var data = {
        "Operate": "GetFiledList",
        "SiteId": SiteId,
        "ChannelId": ChannelId,
        "CMId": CMId,
        "SortField": sortField,
        "IsDesc": isDesc,
        "ParentId": $("#ddlParent button").attr('fid'),

        "IsShow": isShow,
        "Keyword": keyword,
        "PageIndex": page
    };

    $.post("Handler.ashx", data, function (ajaxMsg) {
        if (ajaxMsg.status == 1) {
            var colspan = $tbody.prev().children().eq(0).children().length;
            if ($tbody.children().length > 0) {//如果已有数据，先移去
                $tbody.children().remove();
            }

            if (ajaxMsg.data.length > 0) {
                var html = $.render.listTemplate(ajaxMsg.data);
                $tbody.append(html); //添加数据
                expandAll($('#expendchk'));
                $('#pagination-demo').twbsPagination({//分頁
                    totalPages: ajaxMsg.totalPages,
                    visiblePages: 10,
                    onPageClick: function (event, page) {
                        if (!isFirstLoad) {
                            getFiledList(page);
                        }
                        isFirstLoad = false;
                    },
                    first: txt_FirstPage,
                    prev: txt_PreviousPage,
                    next: txt_NextPage,
                    last: txt_LastPage
                });
            }
            else {
                $("<tr><td colspan='" + colspan + "'>"+txt_NoData+"</td></tr>").appendTo($tbody);
            }
            msgBox.hidBox(); //隐藏消息面板
        }
        else {
            msgBox.showMsgErr(ajaxMsg.msg); //显示消息面板
        }
    }, "json");
}

//刪除字段
//sortField 排序字段
//isDesc 是否是降序
function deleteField() {
    msgBox.showMsgWait(txt_TryingToDelete); //显示消息面板
    var $chkSelects = $("input:checked", $tbody);
    var selectIds = "";
    if ($chkSelects.length === 0) {
        msgBox.showMsgErr(txt_ChoiceOne);
        return;
    }

    for (var i = 0; i < $chkSelects.length; i++) {
        selectIds += $chkSelects.eq(i).val() + ",";
    }

    var isShow = $("#ddlIsShow").val();
    var keyword = $("#txtKeyword").val();

    getSortInfo();

    var data = {
        "Operate": "DeleteFooter",
        "SiteId": SiteId,
        "ChannelId": ChannelId,
        "CMId": CMId,
        "SortField": sortField,
        "IsDesc": isDesc,
        "ParentId": $("#ddlParent").val(),

        "IsShow": isShow,
        "Keyword": keyword,
        "FooterIds": selectIds,
    };

    $.post("Handler.ashx", data, function (ajaxMsg) {
        if (ajaxMsg.status == 1) {
            msgBox.showMsgOk(txt_Success); //显示消息面板
            $('[name="chkSelect"]:checked').parents('tr').remove(); //页面中删除
        } else {
            msgBox.showMsgErr(ajaxMsg.msg); //显示消息面板
        }
    }, "json");
}

//排序
//event 事件對象
function sort(event) {
    var $span = $(event.target);
    var $b = $span.parent().parent();
    var $spanDirection = $span.parent().next();
    if ($b.attr("class") == "")//點擊的不是當前列
    {
        var $tr = $b.parent().parent();
        $tr.find("b").removeClass("hsadisesk");
        $tr.find("[name='spanDirection']").attr("class", "");
        $b.attr("class", "hsadisesk");
        $spanDirection.addClass("glyphicon glyphicon-triangle-bottom");
    }

    if ($spanDirection.hasClass("xuanzhuanss"))//升序
    {
        $spanDirection.removeClass("xuanzhuanss");
        sortField = $span.parent().attr("field");
        isDesc = true;
        getFiledList();
    }
    else {//降序
        $spanDirection.addClass("xuanzhuanss");
        sortField = $span.parent().attr("field");
        isDesc = false;
        getFiledList();
    }
}

//全選
//currObj 當前選中的checkbox
//containerId 容器Id
function selectAll(currObj, containerId) {
    var checked = currObj.checked;
    var $chks = $("input:checkbox", $("#" + containerId));
    for (var i = 0; i < $chks.length; i++) {
        $chks[i].checked = checked;
    }
}

//展开所有的数据
function expandAll(obj) {
    if ($(obj)[0].checked) {
        $('#tbody tr').show();
        $('[src="' + imgSrc1 + '"]').attr('src', imgSrc2); //修改展开的图片
    } else {
        $('#tbody tr[pid!="0"]').hide();
        $('[src="' + imgSrc2 + '"]').attr('src', imgSrc1);
    }
}